package com.sfac.springboot.interceptor;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ViewMappingInterceptor implements HandlerInterceptor {

    public final static Logger LOGGER = LoggerFactory.getLogger(ViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        LOGGER.debug("===== Pre interceptor =====");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {

        LOGGER.debug("===== Post interceptor =====");
        //判断请求是否为接口，如果为接口直接返回
        if(modelAndView == null){
            return;
        }
        //判断页面请求是否为重定向或者转发，如果是则返回
        if( modelAndView.getViewName().startsWith("redirect") ||
            modelAndView.getViewName().startsWith("forward") ){
            return;
        }


        //获取请求路径
        String path = request.getServletPath();
        //判断modelMap中是否有template，如果有则跳过，无则根据请求路径设置template
        String template =(String) modelAndView.getModelMap().get("template");
        if (StringUtils.isBlank(template)){
            modelAndView.getModelMap()
                    .addAttribute("template",path.substring(1, path.length()));

        }
        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {

        LOGGER.debug("===== After interceptor =====");

    }
}
